package com.xbxm.supplier.crm.httputil.http

import io.reactivex.Observer
import io.reactivex.disposables.Disposable

/**
 * Created by joe on 2018/7/2
 */
abstract class BaseObserver<T> : Observer<T> {

    /**
     * 处理除了cookie失效以外所有的业务参数错误返回的结果
     * @throws Exception
     */
    @Throws(Exception::class)
    protected abstract fun onRequestError(message: String?, code: Int)

    /**
     * 返回成功
     * @param t
     */
    protected abstract fun onSuccess(t: T)

    /**
     * 返回失败
     *
     * @param e
     * @throws Exception
     */
    @Throws(Exception::class)
    protected abstract fun onFailure(reson: String?, e: Throwable)


    protected abstract fun onRequestStart(d: Disposable)

    protected fun onRequestEnd() {

    }

    override fun onSubscribe(d: Disposable) {
        onRequestStart(d)
    }

    override fun onNext(t: T) {
        var isInterceptor = false
        for (interceptor in responseInterceptors) {
            isInterceptor = interceptor.interceptor(t)

            if (isInterceptor) {
                break
            }
        }
        //TODO: 等接口定义下来以后根据接口格式判断请求数据，正确；回调 onSuccess，错误回调 onRequestError
        if (isInterceptor) {
            onRequestEnd()
        } else {
            onSuccess(t)
            onRequestEnd()
        }
    }

    override fun onError(e: Throwable) {
        onRequestEnd()
        onFailure(e.message, e)
    }

    override fun onComplete() {

    }

    //    public void showProgressDialog() {
    //        ProgressDialog.show(mContext, false, "请稍后");
    //    }
    //
    //    public void closeProgressDialog() {
    //        ProgressDialog.cancle();
    //    }


    companion object {
        @JvmStatic
        val responseInterceptors: MutableList<ResponseInterceptor> = mutableListOf<ResponseInterceptor>()
    }
}

interface ResponseInterceptor {
    fun <T> interceptor(t: T): Boolean
}